/*
 * Copyright (C) 2014 Mobs & Geeks
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the
 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mobsandgeeks.saripaar.slice;


import com.mobsandgeeks.saripaar.QuickRule;
import com.mobsandgeeks.saripaar.ResourceTable;
import com.mobsandgeeks.saripaar.ValidationError;
import com.mobsandgeeks.saripaar.Validator;
import com.mobsandgeeks.saripaar.annotation.NotEmpty;
import com.mobsandgeeks.saripaar.annotation.Order;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.app.Context;

import java.util.List;

/**
 * @author Ragunath Jawahar {@literal <rj@mobsandgeeks.com>}
 */
public class QuickRuleUnorderedInOrderedSlice extends Ability
        implements Validator.ValidationListener, AbsButton.CheckedStateChangedListener,
                Component.ClickedListener {

    @NotEmpty
    @Order(1)
    private TextField mZipCodeEditText;

    @Order(2)
    private TextField mAirtelNumberEditText;

    private Text
         mResultTextView;
    private RadioButton mUseQuickRuleRadioButton;
    private Button mSaripaarButton;

    // Attributes
    private Validator mValidator;

     @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_slice_quick_rule_unordered_in_ordered);

        // UI References
        mZipCodeEditText = (TextField) findComponentById(ResourceTable.Id_zipCodeEditText);
        mAirtelNumberEditText = (TextField) findComponentById(ResourceTable.Id_airtelNumberEditText);
        mResultTextView = (Text
        ) findComponentById(ResourceTable.Id_resultTextView);
        mUseQuickRuleRadioButton = (RadioButton) findComponentById(ResourceTable.Id_useQuickRuleRadioButton);
        mSaripaarButton = (Button) findComponentById(ResourceTable.Id_saripaarButton);

        // Validator
        mValidator = new Validator(this);
        mValidator.setValidationListener(this);

        // Quick Rule for ORDERED field
        mValidator.put(mAirtelNumberEditText, new QuickRule<Text
        >() {

            @Override
            public boolean isValid(Text
         Text) {
                final String phoneNumber = Text.getText().toString().trim();
                return phoneNumber.length() == 10 && phoneNumber.startsWith("999");
            }

            @Override
            public String getMessage(Context context) {
                return "Not an Airtel number :(";
            }
        });

        // Event Listeners
        mUseQuickRuleRadioButton.setCheckedStateChangedListener(this);
        mSaripaarButton.setClickedListener(this);
    }

    @Override
    public void onValidationSucceeded() {
        mResultTextView.setText("success");
    }

    @Override
    public void onValidationFailed(List<ValidationError> errors) {
        mResultTextView.setText(Common.getFailedFieldNames(errors));
    }

    @Override
    public void onCheckedChanged(AbsButton buttonView, boolean isChecked) {
         if (isChecked ){
            TextField evenNumberEditText = (TextField) findComponentById(ResourceTable.Id_evenNumberEditText);
            QuickRule<Text
        > evenNumberQuickRule = getEvenNumberQuickRule();

            try {
                mValidator.put(evenNumberEditText, evenNumberQuickRule);
            } catch (IllegalStateException e) {
                mResultTextView.setText("CRASH");
            }
        }
    }

    @Override
    public void onClick(Component component) {
        mValidator.validate();
    }

    private QuickRule<Text
        > getEvenNumberQuickRule() {
        return new QuickRule<Text
        >() {

            @Override
            public boolean isValid(Text Text) {
                String numberText = Text.getText().toString().trim();

                boolean isEven;
                try {
                    isEven = Integer.parseInt(numberText) % 2 == 0;
                } catch (NumberFormatException e) {
                    isEven = false;
                }

                return isEven;
            }

            @Override
            public String getMessage(Context context) {
                return "Not an even number.";
            }
        };
    }
}
